<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Goods;
use app\common\model\order\Order as ModelOrder;
use app\common\model\order\Review;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\user\Credit;
use think\Db;
use think\Validate;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['review_list'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (下单)
     * @ApiMethod (POST)
     * @ApiParams (name="share_uid", type="integer", required=true, sample="", description="分享用户ID")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品ID")
     * @ApiParams (name="senddate", type="string", required=true, sample="", description="送货时间")
     * @ApiParams (name="takedate", type="string", required=true, sample="", description="取货时间")
    //  * @ApiParams (name="address_id", type="string", required=true, sample="", description="送货地址ID")
     * @ApiParams (name="take_address_id", type="string", required=true, sample="", description="取货货地址ID")
     * @ApiParams (name="shop_id", type="string", required=true, sample="", description="门店ID")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量")
     * @ApiParams (name="order_type", type="string", required=true, sample="", description="订单类型:1=上门取送,2=到店自送")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_order()
    {
        $param = request()->param();
        extract($param);
        // if (!isset($senddate) || !$senddate) {
        //     $this->error('请选择送货时间');
        // }
        if ($order_type == 1) {
            if (!isset($takedate) || !$takedate) {
                $this->error('请选择取鞋时间');
            }
        }
        if (!isset($num) || $num <= 0) {

            $this->error('购买数量错误');
        }
        if ($order_type==1) {
            $take_address = Address::get($take_address_id);
            if (!$take_address) {
                $this->error('取鞋地址不存在');
            }
        }
        // $addressInfo = Address::get($address_id);
        // if (!$addressInfo) {
        //     $this->error('地址不存在');
        // }
        $goodsInfo = Goods::get($goods_id);
        if (!$goodsInfo) {
            $this->error('商品不存在');
        }
        Db::startTrans();
        try {
            $shop_info = User::get($shop_id);
            $data = [
                'user_id' => $this->auth->id,
                // 'address_id' => $address_id,
                'take_address_id' => $take_address_id ?? 0,
                'shop_id' => $shop_id,
                'shop_address' => $shop_info ? json_encode($shop_info) : '',
                'take_address' => $take_address ? json_encode($take_address) : '',
                'share_uid' => $share_uid,
                // 'contact' => $addressInfo->contact,
                // 'telephone' => $addressInfo->telephone,
                // 'city' => $addressInfo->city,
                // 'address' => $addressInfo->address,
                // 'address_lng' => $addressInfo->lng,
                // 'address_lat' => $addressInfo->lat,
                'order_type' => $order_type,
                // 'senddate' => $senddate ?? '',
                'takedate' => $takedate ? $takedate : null,
                'goods_id' => $goods_id,
                'goods_name' => $goodsInfo->title,
                'goods_image' => $goodsInfo->image,
                'goods_description' => $goodsInfo->description,
                'goods_price' => $goodsInfo->price,
                'num' => $num,
                'total_fee' => bcmul($goodsInfo->price, $num, 2),
                'orderid' => sn('order', 'orderid', 'NO'),
            ];

            $order = new ModelOrder($data);
            $order->allowField(true)->save();
            if ($order->id) {
                queue('app/common/job/CancelOrder', $order->id, 900, 'CancelOrder1274');
            } else {
                exception('下单失败');
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('', $order->id);
    }

    /**
     * @Author LK
     * @ApiTitle (订单列表)
     * @ApiMethod (get)
     * @ApiParams (name="order_status", type="integer", required=true, sample="", description="all=全部,0=待支付,10=待取鞋/待自送,15=待清洁,20=清洁中,30=待配送,40=配送中,50=已完成,60=已评价")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {
        $param = request()->param();
        extract($param);
        $order = new ModelOrder;
        if ($order_status != 'all') {
            if ($order_status == '50') {
                $order->whereIn('order_status', ['50', '60']);
            }else{
                $order->where('order_status', $order_status);
            }
        }
        
        $list = $order->with(['user', 'take', 'send', 'goods'])->where('order_status', '<>', '-1')->where('order.user_id', $this->auth->id)->order('order.id desc')->paginate();
        $this->success('请求成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $info = ModelOrder::get($id, ['user', 'take', 'send', 'goods']);
        $credit = Credit::get(['user_id' => $info->user_id, 'goods_id' => $info->goods_id]);
        $info->credit_num = isset($credit->num) ? $credit->num : 0;
        $this->success('请求成功', $info);
    }

    /**
     * @Author LK
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $param = request()->param();
        extract($param);
        $info = ModelOrder::get($id);
        $info->order_status = '-1';
        $info->save();
        $this->success('取消成功');
    }

    /**
     * @Author LK
     * @ApiTitle (订单评论)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="订单ID")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品ID")
     * @ApiParams (name="star", type="integer", required=true, sample="", description="评分")
     * @ApiParams (name="content", type="string", required=true, sample="", description="描述")
     * @ApiParams (name="images", type="string", required=true, sample="", description="图片")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_review()
    {
        $param = request()->param();
        extract($param);
        $validate = new Validate([
            'id'   => 'require|gt:0',
            'goods_id'  => 'require|gt:0',
            'star'  => 'require|gt:0',
            'content'  => 'require',
            'images'  => 'require',
        ], [
            'id.require'  => '订单不能为空',
            'goods_id.require' => '商品不能为空',
            'star.require' => '评分不能为空',
            'content' => '描述不能为空',
            'images' => '请上传评价图片',
        ]);
        $result =  $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $order = ModelOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        Db::startTrans();
        try {
            $param['user_id'] = $this->auth->id;
            $param['order_id'] = $param['id'];
            unset($param['id']);
            $model = new Review($param);
            $res = $model->allowField(true)->save();
            if ($res) {
                $order->order_status = '60';
                $order->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('评价成功');
    }
    /**
     * @Author LK
     * @ApiTitle (评论列表)
     * @ApiMethod (get)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function review_list()
    {
        $param = request()->param();
        extract($param);
        $list = Review::with('user')->where('goods_id', $id)->paginate($limit);
        return $this->success('', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (修改订单地址)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="订单ID")
     * @ApiParams (name="take_address_id", type="integer", required=true, sample="", description="取货地址ID")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="送货地址ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function edit_address()
    {
        $param = request()->param();
        extract($param);
        $order =  ModelOrder::get(['id' => $id, 'order_status' => '0']);
        if (!$order) {
            $this->error('订单不存在');
        }
        try {
            if ($take_address_id) {
                $take_address = Address::get($take_address_id);
                $order->take_address = $take_address ? json_encode($take_address) : '';
            }
            // if ($address_id) {
            //     $order->address_id = $address_id;
            // }
            $order->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('修改成功');
    }
}
